mod proxy;
mod stub;

use log::{error, info};
use std::io;
use ylong_runtime::net::{TcpListener, TcpStream};

use crate::Param;
use proxy::Proxy;
use stub::usb::usb_manager;

pub async fn start_server(param: &Param) {
    ylong_runtime::spawn(async {
        let _ = ylong_runtime::spawn_blocking(|| {usb_manager::usb_backend_daemon()}).await;
    });
    let _ = start_client_listen(param.get_server_add()).await;
}

async fn start_client_listen(addr_str: String) -> io::Result<()> {
    let saddr = addr_str;
    let listener = TcpListener::bind(saddr.clone()).await?;
    info!("server binds on {saddr}");

    loop {
        let (stream, addr) = listener.accept().await?;
        info!("accepted client {addr}");
        ylong_runtime::spawn(handle_client(stream));
    }
}
async fn handle_client(stream: TcpStream) -> io::Result<()> {
    let Some(mut porxy) = Proxy::new(stream).await else {
        error!("porxy new error");
        return Ok(());
    };
    loop {
        if let Err(_err) = porxy.run_task().await {
            break;
        }
    }
    Ok(())
}
